package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


/*
 * @Author: jun
 * @Date:2022/11/25 14:16
 * @概述：
 */


@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserMapper userMapper;
    @PostMapping
//    Result中的?号表示任何类型
    public Result<?> save(@RequestBody User user){
        userMapper.insert(user);
        return Result.success();
    }

    /**
     * 查找到所有的数据并且渲染到前端页面
     * @param pageNum
     * @param pageSize
     * @param search
     * @return
     */
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){

        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
        if (StrUtil.isNotBlank(search)){
            wrapper.like(User::getNickName, search);
        }
        Page<User> p = userMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(p);
    }


    /**
     * 更新数据
     * @param user
     * @return
     */
    @PutMapping
    public Result<?> update(@RequestBody User user){
        userMapper.updateById(user);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id){
        userMapper.deleteById(id);
        return Result.success();
    }

    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result<?> login(@RequestBody User user){
//        lambda表达式eq验证用户名和密码是否正确
        User result = userMapper.selectOne(
                Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()).eq(User::getPassword, user.getPassword()));
        if (result == null){
            return Result.error("-1","用户名或密码错误");
        }
        return Result.success();
    }
}
